import 'package:flutter_again/database/database_helper.dart';
import 'package:flutter_again/models/website_link.dart';
import 'package:flutter_again/models/repository.dart';
import 'package:flutter_again/utils/setup.dart';
import 'package:logger/logger.dart';

class WebsiteLinkDao implements Repository<WebsiteLink, int, CreateWebsiteLinkRequest, UpdateWebsiteLinkRequest> {
  final tableName = 'website_links';

  @override
  read() async {
    final db = await getIt<DatabaseHelper>().database;
    final maps = await db.query(tableName);
    getIt<Logger>().d('maps: $maps');
    return maps.map((item) => WebsiteLink.fromJson(item)).toList();
  }
  @override
  create(link) async {
    final db = await getIt<DatabaseHelper>().database;
    final id = await db.insert(tableName, link.toJson());
    return await readById(id) as WebsiteLink;
  }
  @override
  update(link) async {
    final db = await getIt<DatabaseHelper>().database;
    await db.update(
      tableName,
      link.toJson(),
      where: 'id = ?',
      whereArgs: [link.id],
    );
    return await readById(link.id) as WebsiteLink;
  }
  @override
  readById(id) async {
    final db = await getIt<DatabaseHelper>().database;
    final result = await db.query(
      tableName,
      where: 'id = ?',
      whereArgs: [id],
    );
    return result.isNotEmpty ? WebsiteLink.fromJson(result[0]) : null;
  }
  // 删除
  @override
  delete(link) async {
    final db = await getIt<DatabaseHelper>().database;
    await db.delete(
      tableName,
      where: 'id = ?',
      whereArgs: [link.id],
    );
    return link;
  }

}
